package com.sky.controller;

import com.sky.result.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/admin/images")
public class ImageController {

    @Value("${visa.path.user-material-images}")
    private String userMaterialImagesPath;

    @Value("${visa.path.image-base-url}")
    private String imageBaseUrl;

    @PostMapping("/usermaterial/upload")
    public Result<String> uploadUserMaterialImage(@RequestParam("file") MultipartFile file) {
        try {
            Path dirPath = Paths.get(userMaterialImagesPath);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }

            String originalFilename = file.getOriginalFilename();
            // 处理微信小程序的临时文件路径
            if (originalFilename != null && originalFilename.startsWith("wxfile://")) {
                // 从临时文件路径中提取文件名
                originalFilename = originalFilename.substring(originalFilename.lastIndexOf("/") + 1);
            }
            
            // 确保文件名有扩展名
            String extension;
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            } else {
                // 如果没有扩展名，根据文件类型判断
                String contentType = file.getContentType();
                if (contentType != null && contentType.startsWith("image/")) {
                    extension = "." + contentType.substring(contentType.lastIndexOf("/") + 1);
                } else {
                    extension = ".jpg"; // 默认扩展名
                }
            }

            String fileName = UUID.randomUUID().toString() + extension;
            Path filePath = dirPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            String fileUrl = imageBaseUrl + "/images/usermaterial/" + fileName;
            if (imageBaseUrl.endsWith("/")) {
                fileUrl = imageBaseUrl + "images/usermaterial/" + fileName;
            }
            return Result.success(fileUrl);
        } catch (Exception e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
}